import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/entity/data/team_entiy.dart';
import 'package:ball_lion/entity/data/team_focus_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/server/api/data_api.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/utils/toast_utils.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/widgets/ball_appbar.dart';

import 'package:ball_lion/widgets/base/wqs_dialog.dart';

import 'package:ball_lion/server/api/user_api.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';

class My2FocusTeamPage extends StatefulWidget {
  const My2FocusTeamPage({super.key});

  @override
  State<My2FocusTeamPage> createState() => _My2FocusTeamPageState();
}

class _My2FocusTeamPageState extends State<My2FocusTeamPage> {
  List<FocusTeamListEntity> list = [];
  FocusTeamListEntity? selectTeam;
  List<MyTeamFocusEntity> get teams => selectTeam?.teamList ?? [];

  getTeams() async {
    list = await DataApi.teamForSelect() ?? [];
    if (list.isNotEmpty) {
      selectTeam = list.first;
    }
    update();
  }

  focusOrNot(MyTeamFocusEntity team) async {
    if (team.id == null) {
      return;
    }
    if (team.focus == 0) {
      Utils.onEvent('wd_wdgz_gzan', params: {'wd_wdgz_gzan': '4'});
      final result = await UserApi.focusTeam(team.id!, 1);
      if (result == 200) {
        team.focus = 1;
        update();
      }
    } else {
      if (!await Get.dialog(QsDialog.alert("确认不再关注？"))) {
        return;
      }
      final r = await UserApi.unFocusTeam(team.id!, 1);
      if (r == 200) {
        team.focus = 0;
        update();
      } else {
        Toast.text("取消关注失败");
      }
    }
  }

  @override
  void initState() {
    getTeams();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colours.scaffoldBg,
      appBar: const BallAppBar(title: "关注球队"),
      body: Row(
        children: [leftSide(), Expanded(child: rightSide())],
      ),
    );
  }

  Widget leftCell(FocusTeamListEntity list) {
    final select = list == selectTeam;
    int num = 0;
    for (var element in list.teamList ?? []) {
      if (element.focus != 0) {
        num += 1;
      }
    }
    String name = list.leagueName ?? "";
    if (num != 0) {
      name = "${list.leagueName}($num)";
    }
    return Stack(
      children: [
        Container(
          color: select ? Colours.white : null,
          height: 60,
          alignment: Alignment.center,
          child: QsText(name),
        ).tap(() {
          selectTeam = list;
          update();
        }),
        if (select)
          Positioned(
              left: 0,
              top: 18,
              bottom: 18,
              child: Container(
                width: 3,
                height: 24,
                decoration: const BoxDecoration(
                    color: Colours.main,
                    borderRadius:
                        BorderRadius.horizontal(right: Radius.circular(3))),
              ))
      ],
    );
  }

  Widget leftSide() => Container(
        width: 80,
        child: ListView(
          children: [...list.map((e) => leftCell(e))],
        ),
      );

  Widget rightCell(MyTeamFocusEntity team) => Container(
        padding: EdgeInsets.only(left: 20, right: 16),
        height: 50,
        child: Row(
          children: [
            Row(
              children: [
                Container(
                  clipBehavior: Clip.hardEdge,
                  width: 24,
                  height: 24,
                  decoration:
                      BoxDecoration(borderRadius: BorderRadius.circular(2)),
                  child: CachedNetworkImage(
                    imageUrl: team.logo ?? "",
                    placeholder: (context, url) => Styles.placeholderIcon(),
                    errorWidget: (context, url, error) =>
                        Styles.placeholderIcon(),
                  ),
                ).marginOnly(right: 12),
                QsText(team.nameChsShort ?? ""),
              ],
            ).tap(() {
              Utils.onEvent('wd_wdgz_gzan', params: {'wd_wdgz_gzan': '5'});
              Get.toNamed(Routes.zqTeamDetail, arguments: team.id);
            }),
            const Spacer(),
            Container(
              width: 56,
              height: 24,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                  border: Border.all(
                      color: team.focus == 0 ? Colours.main : Colours.grey99,
                      width: 0.5),
                  borderRadius: BorderRadius.circular(4)),
              child: QsText(team.focus == 0 ? "关注" : "已关注",
                  color: team.focus == 0 ? Colours.main : Colours.grey99,
                  fontSize: 13),
            ).tap(() {
              focusOrNot(team);
            })
          ],
        ),
      );

  Widget rightSide() => Container(
        color: Colours.white,
        child: ListView(
          children: [...teams.map((e) => rightCell(e))],
        ),
      );
}
